import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import redis.clients.jedis.Jedis;


@WebServlet("/del_prompt")

public class DelPrompt extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        String id = req.getParameter("id");
        if (id == null) {
            throw new ServletException("please input id");
        }

        // 1.在redis中删除key为此id的数据
        /*
            请完善代码
        */
        Jedis jedis = new Jedis("localhost", 6379);
        jedis.del(id);
        jedis.close();
        // 2.删除数据库中此id的数据
        delPrompt(getJDBCConnection(), id);

        PrintWriter out = resp.getWriter();
        out.printf("[del]ok");
        out.close();

    }

    public void delPrompt(final Connection conn, String id) throws ServletException {
        /*
            请完善代码
        */
        String sql = "DELETE FROM t_ai_painting WHERE id = ?";
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("删除成功");
            } else {
                System.out.println("删除失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServletException("删除数据失败");
        }
    }

}
